<?php
/*
 * @component AlphaUserPoints
 * @copyright Copyright (C) 2008-2010 Bernard Gilly
 * @license : GNU/GPL
 * @Website : http://www.alphaplug.com
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class alphauserpointsModelvalidate_payment extends Jmodel {

	function __construct(){
		parent::__construct();
		
	}
	
	function validatePDT( &$params, $tx_token, $referrerid )
	{	

		require_once (JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helper.php');
		
		$msg = "";
		$success = 1;
		$keyarray = array();	

		if ( $tx_token ) 
		{
			$db       = JFactory::getDBO();			
	
			// Paypal account
			if ( $params->get( 'usepaypaltestaccount' ) )
			{
				// Use test mode
				$paypal   = "www.sandbox.paypal.com";
				$business = $params->get('testaccountmail', '');
				$auth_token = $params->get('testtoken', '');
			}
			else
			{
				// Use real Paypal account
				$paypal = "www.paypal.com";
				$business = $params->get('businessmail', '');
				$auth_token = $params->get('businesstoken', '');
			}		
			
			// read the post from PayPal system and add 'cmd'
			$req = 'cmd=_notify-synch';
			$req .= "&tx=".urlencode($tx_token)."&at=".urlencode($auth_token);		
	
			// post back to PayPal system to validate
			$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
			$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
			$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
			$fp = fsockopen ($paypal, 80, $errno, $errstr, 30);
			
			// assign posted variables to local variables
			//$item_name = $_POST['item_name'];
			//$item_number = $_POST['item_number'];
			//$payment_status = $_POST['payment_status'];
			//$payment_currency = $_POST['mc_currency'];
			//$txn_id = $_POST['txn_id'];
			//$receiver_email = $_POST['receiver_email'];
			//$payer_email = $_POST['payer_email'];
			//$custom = $_POST['custom'];
			//$num_cart_items = $_POST['num_cart_items'];
			//$amount = $_POST['mc_gross'];
			
			if (!$fp) {
				// HTTP ERROR
				$success = 0;
				$msg = JText::_('AUP_HTTP_ERROR');
			} else {
				fputs ($fp, $header . $req);
				// read the body data 
				$res = '';
				$headerdone = false;
				while (!feof($fp)) {
					$line = fgets ($fp, 1024);
					if (strcmp($line, "\r\n") == 0) 
					{
						// read the header
						$headerdone = true;
						//echo$headerdone;
					}
					else if ($headerdone)
					{ 
						// header has been read. now read the contents
						$res .= $line;
					}
				}			
		 
				// parse the data
				$lines = explode("\n", $res);
				if (strcmp ($lines[0], "SUCCESS") == 0) 
				{
				 
					for ($i=1; $i<count($lines);$i++)
					{
						@list($key,$val) = explode("=", $lines[$i]);
						$keyarray[urldecode($key)] = urldecode($val);
					}				 
					//print_r($keyarray);					 
					//$num_cart_items = $keyarray['num_cart_items'];
					//$firstname = $keyarray['first_name'];
					//$lastname = $keyarray['last_name'];
					$txn_id = $keyarray['txn_id'];
					//$amount = $keyarray['mc_gross'];
					//$payment_date = $keyarray['payment_date'];
					//$payment_currency = $keyarray['mc_currency'];
					//$product_name = $keyarray['item_name'];
					
					// check if not transaction already processed
					$query = "SELECT id FROM #__alpha_userpoints_details WHERE `keyreference`='$txn_id' LIMIT 1";
					$db->setQuery($query);
					$alreadyexist = $db->loadResult();
					if ( $alreadyexist )
					{
						$success = 0;
						$msg = JText::_('AUP_THIS_TRANSACTION_WAS_ALREADY_PROCESSED');
					}
					 else
					{
						$success = 1;
						$msg = "";
						// insert points in database
						$datas = JText::_('AUP_BUY_NEW_POINTS') . " &raquo; " . $keyarray['custom'] . " " . JText::_('AUP_POINTS') . " - " . $keyarray['payment_date'] . " -  Paypal ID " . $keyarray['txn_id'] ;
						// insert purchased points
						AlphaUserPointsHelper::newpoints( 'sysplgaup_buypointswithpaypal', $referrerid, $keyarray['txn_id'], $datas, $keyarray['custom']);
					}
	
				}
				else if (strcmp ($lines[0], "FAIL") == 0) 
				{		 
						
					$success = 0;
					$msg = JText::_('AUP_VERIFICATION_FAILED') . " " . JText::_('AUP_VERIFICATION_FAILED_DESCRIPTION');					
					
					/************************************
					
					    NO POINT INSERTED IN DATABASE
					
					*************************************/					
					
					// insert Points in database but must be verified manualy -> set not approved
					/*
					$jnow		=& JFactory::getDate();
					$now		= $jnow->toMySQL();
					
					$datareference = JText::_('AUP_BUY_NEW_POINTS') . " &raquo; " . $pointspurchased . " " . JText::_('AUP_POINTS') . " - " . $now . " -  Paypal ID " . $tx_token . " - <font color=red>" . JText::_('AUP_THIS_PAYMENT_MUST_BE_VERIFIED') . "</font>";
					$result = AlphaUserPointsHelper::checkRuleEnabled( 'sysplgaup_buypointswithpaypal' );

					if ( $referrerid && $tx_token && $result )
					{
						AlphaUserPointsHelper::insertUserPoints( $referrerid, $pointspurchased, $result[0]->rule_expire, $result[0]->id, 0, $tx_token, $datareference, 0, $result[0]->plugin_function );
					}
					*/					
				}
				
			}
			
			fclose ($fp);
	
		}
		
		$response->success = $success;
		$response->msg = $msg;
		
		return array($response, $keyarray);		
	
	}
	
}
?>